package gwt.coonay.client;

import gwt.common.RichTextToolbar;

import java.util.Date;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONException;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RichTextArea;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Home implements EntryPoint {

	Label lGmail = new Label();
	private Label errorMsgLabel = new Label();
	private Label debugLabel = new Label();
	private Anchor signAnchor = new Anchor("Sign in", "");
	private Label latestLabel = new Label("Latest:");

	private HorizontalPanel notePanel = new HorizontalPanel();

	private VerticalPanel contentPanel = new VerticalPanel();

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {

		HorizontalPanel headerPanel = new HorizontalPanel();

		this.createHead(headerPanel);

		errorMsgLabel.setWidth("100%");
		debugLabel.setWidth("100%");

		notePanel.setWidth("100%");
		this.createNote(notePanel);

		VerticalPanel rightPanel = new VerticalPanel();
		HorizontalPanel mainPanel = new HorizontalPanel();
		mainPanel.setWidth("100%");
		mainPanel.add(contentPanel);
		mainPanel.add(rightPanel);

		this.createContent();
		this.createRightContent(rightPanel);

		HorizontalPanel footPanel = new HorizontalPanel();
		createFoot(footPanel);

		RootPanel root = RootPanel.get();
		root.add(headerPanel);
		errorMsgLabel.setVisible(false);
		root.add(errorMsgLabel);
		root.add(debugLabel);
		root.add(notePanel);

		root.add(mainPanel);

		root.add(footPanel);

		requestData();
	}

	private void createNote(HorizontalPanel notePanel) {
		final RichTextArea noteArea = new RichTextArea();
		noteArea.setWidth("70%");
		noteArea.setHeight("3em");
		noteArea
				.setText("Type your new message here                            ");
		// RichTextToolbar toolbar = new RichTextToolbar(noteArea);
		// notePanel.add(toolbar);
		notePanel.setSpacing(150);
		notePanel.add(noteArea);

		Button postButton = new Button("Post");
		notePanel.add(postButton);
		// notePanel.setCellWidth(noteArea,"60%");

		notePanel.setVisible(false);

		postButton.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				String post = noteArea.getText();
				if (post != null && post.length() > 0) {
					if (!post.startsWith("Type your new message here")) {
						final VerticalPanel postPanel = new VerticalPanel();
						Label time = new Label(new Date().toString());
						Label p = new Label(post);

						HorizontalPanel actionPanel = new HorizontalPanel();
						Label who = new Label("By " + lGmail.getText());
						

						final Button delButton = new Button("Del");
						delButton.addClickListener(new ClickListener() {
							public void onClick(Widget sender) {

								delButton.setEnabled(false);
								final DialogBox d = new DialogBox();
								d.setHeight("50%");
								d.setWidth("50%");

								d.setText("Are u sure to delete this post?");
								Label details = new Label("There is NO undo");
								VerticalPanel dialogContents = new VerticalPanel();
								dialogContents.setSpacing(4);
								d.setWidget(dialogContents);
								dialogContents.add(details);
								dialogContents.setCellHorizontalAlignment(
										details,
										HasHorizontalAlignment.ALIGN_CENTER);

								// Add a close button at the bottom of the
								// dialog
								Button closeButton = new Button("Close",
										new ClickListener() {
											public void onClick(Widget sender) {

												delButton.setEnabled(true);
												d.hide();

											}
										});

								Button deleteButton = new Button("Delete",
										new ClickListener() {
											public void onClick(Widget sender) {
												contentPanel.remove(postPanel);
												d.hide();
											}
										});

								Grid grid = new Grid(1, 2);
								grid.setWidget(0, 0, deleteButton);
								grid.setWidget(0, 1, closeButton);

								dialogContents.add(grid);
								dialogContents.setCellHorizontalAlignment(grid,
										HasHorizontalAlignment.ALIGN_CENTER);

								d.center();
								d.show();
							}
						});

						actionPanel.setSpacing(10);
						actionPanel.add(who);
						
						actionPanel.add(delButton);

						postPanel.add(time);
						postPanel.add(p);
						postPanel.add(actionPanel);

						sendUpdate(post);
						latestLabel.setText("Latest:" + post);

						contentPanel.insert(postPanel, 1);
						noteArea
								.setText("Type your new message here                            ");
					}
				}
			}
		});

		noteArea.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				String post = noteArea.getText();
				if (post != null && post.length() > 0) {
					if (post.startsWith("Type your new message here "))
						noteArea.setText("");

				}
			}
		});

	}

	private void createContent() {
		contentPanel.setWidth("65%");

		contentPanel.add(latestLabel);
		StringBuffer b = new StringBuffer();
		b
				.append("<br>[BlackBoard]: Hot:<a href=\"http://devatlab.appspot.com/\" target=\"new\">BroadCasting you</a><br><br>[TaskForce]: Hot:<a href=\"http://code.google.com/p/coonay/wiki/CoonayWiki\" target=\"new\">		  Your contribution is wanted</a><br>Posted On 2/10/2009<br><br>[TechInside] :<a href=\"http://groups.google.com/\" target=\"\">Groups</a>");
		b
				.append("&nbsp | &nbsp <a href=\"http://docs.djangoproject.com/\" target=\"\">Django</a>");
		b
				.append("&nbsp | &nbsp <a href=\"http://code.google.com/appengine/\" target=\"new\">GAE</a>");
		b
				.append("&nbsp | &nbsp <a href=\"http://code.google.com/appengine/\" target=\"new\">GAE</a>");
		b
				.append("&nbsp | &nbsp <a href=\"http://code.google.com/webtoolkit/\" target=\"new\">GWT</a>");
		b
				.append("<br><br><br><br>[Voice] :To make it better, <a href=\"http://devatlab.appspot.com/\" target=\"new\">Talk with me</a><br>");

		HTML f = new HTML(b.toString());
		f.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT);
		HTML f1 = new HTML(b.toString());
		f1.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT);
		HTML f2 = new HTML(b.toString());
		f2.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT);

		contentPanel.add(f);
		contentPanel.add(f1);
		contentPanel.add(f2);

	}

	private void createRightContent(final VerticalPanel rightPanel) {
		rightPanel.setWidth("32%");
		Label psnLabel = new Label("Profile:");
		rightPanel.add(psnLabel);

		StringBuffer b = new StringBuffer();
		b.append("Please <a href=\"{{sign_url}}\">sign in</a> to post note");
		HTML h = new HTML(b.toString());
		rightPanel.add(h);

		Label stuffLabel = new Label("My Stuff:");
		rightPanel.add(stuffLabel);
		b.delete(0, b.length());
		b
				.append("<br><button style=\"width:10em\" type=\"button\">Post Note</button>");
		// b.append(
		// "<button style=\"width:10em\" type=\"button\" onClick=\"window.location='/notes'\">Topics</button>"
		// );
		h = new HTML(b.toString());
		rightPanel.add(h);
		final Label r = new Label("*Please sign in");
		rightPanel.add(r);
		r.setVisible(false);
		h.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				// if ( lGmail != null && lGmail.getText().length() > 0 )
				{

					r.setVisible(true);
					notePanel.setVisible(true);
				}
			}
		});

	}

	private void createFoot(HorizontalPanel footPanel) {
		HTML f = new HTML(
				"<hr/>International Coonay:<a href=\"/\">North America</a> - E.U. - China - Korea | <a href=\"http://devatlab.appspot.com/\" target=\"new\">MicBlog</a><br>@2009 Coonay<a href=\"/\">Home</a> - <a href=\"/help\">Help</a> - <a href=\"http://devatlab.appspot.com/\" target=\"new\">Contact</a>");

		f.setHorizontalAlignment(HorizontalPanel.ALIGN_CENTER);
		footPanel.add(f);
		footPanel.setWidth("100%");

	}

	private void createHead(HorizontalPanel headerPanel) {
		Image img = new Image("images/coonay.jpg");

		Anchor aMicBlog = new Anchor("MicBlog", "http://devatlab.appspot.com/",
				"new");
		Anchor aWriteWeb = new Anchor("WriteWeb",
				"http://sites.google.com/site/flankw/", "new");

		HorizontalPanel navPanel = new HorizontalPanel();
		navPanel.setSpacing(18);
		navPanel.add(lGmail);
		navPanel.add(aMicBlog);
		Label l = new Label("|");
		navPanel.add(l);
		navPanel.add(aWriteWeb);
		l = new Label("|");
		navPanel.add(l);
		navPanel.add(signAnchor);

		headerPanel.add(img);
		headerPanel.setCellHorizontalAlignment(img, HorizontalPanel.ALIGN_LEFT);
		headerPanel.add(navPanel);
		headerPanel.setCellHorizontalAlignment(navPanel,
				HorizontalPanel.ALIGN_RIGHT);
		headerPanel.setWidth("100%");
	}

	/**
	 * If can't get JSON, display error message.
	 * 
	 * @param error
	 */
	private void displayError(String error) {
		errorMsgLabel.setText("Error: " + error);
		errorMsgLabel.setVisible(true);
	}

	/**
	 * If can't get JSON, display error message.
	 * 
	 * @param error
	 */
	private void debug(String info) {
		debugLabel.setText(debugLabel.getText() + "Debug:" + new Date() + " "
				+ info);

	}

	private void disableDebug() {
		debugLabel.setVisible(false);
	}
	
	
	private void sendUpdate(String note)
	{
		final String JSON_URL = "/gwt/Home/update?note="+note;
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET,
				JSON_URL);
		
		try {
			builder.sendRequest(null, new RequestCallback() {
				public void onError(Request request, Throwable exception) {
					displayError("Couldn't retrieve update");
				}

				public void onResponseReceived(Request request,
						Response response) {
					if (200 == response.getStatusCode()) {
						debug("update=" + response.getText());

						updateHome(response.getText());

					} else {
						displayError("Couldn't retrieve update ("
								+ response.getStatusText() + ")");
					}
				}
			});
		} catch (RequestException e) {
			displayError("Couldn't retrieve JSON");
		} catch (com.google.gwt.core.client.JavaScriptException jse) {
			displayError("Couldn't retrieve JSON (" + jse.getMessage() + ")");
		}

	}
	
	

	private void requestData() {
		// final String JSON_URL = GWT.getModuleBaseURL();
		final String JSON_URL = "/gwt/Home";
		// Send request to server and catch any errors.
		RequestBuilder builder = new RequestBuilder(RequestBuilder.POST,
				JSON_URL);
		try {
			builder.sendRequest(null, new RequestCallback() {
				public void onError(Request request, Throwable exception) {
					displayError("Couldn't retrieve JSON");
				}

				public void onResponseReceived(Request request,
						Response response) {
					if (200 == response.getStatusCode()) {
						debug("response=" + response.getText());

						updateHome(response.getText());

					} else {
						displayError("Couldn't retrieve JSON ("
								+ response.getStatusText() + ")");
					}
				}
			});
		} catch (RequestException e) {
			displayError("Couldn't retrieve JSON");
		} catch (com.google.gwt.core.client.JavaScriptException jse) {
			displayError("Couldn't retrieve JSON (" + jse.getMessage() + ")");
		}

	}

	void updateHome(String json) {
		// Clear any errors.
		errorMsgLabel.setVisible(false);
		try {
			// parse the response text into JSON
			JSONValue jsonValue = JSONParser.parse(json);
			JSONArray jsonArray = jsonValue.isArray();
			if (jsonArray != null) {
				JSONObject jso = jsonArray.get(0).isObject();
				JSONObject jso1 = jsonArray.get(1).isObject();
				if (jso != null) {
					JSONString jss = jso.get("gmail").isString();
					String gmail = jss.stringValue();

					lGmail.setText(gmail);
					if (gmail != null && gmail.length() > 0) {
						signAnchor.setText("Sign out");
					} else {
						signAnchor.setText("Sign in");
					}
					jss = jso1.get("sign_url").isString();
					signAnchor.setHref(jss.stringValue());

				}
			}
		} catch (JSONException jse) {
			this.displayError(jse.getMessage());
		}

	}

}
